import cv2
import numpy as np
import win32api
import win32gui
import win32con
from PIL import ImageGrab
import time
import random
import sys
import os
import pyautogui
import autopy
import operator
import torch
from detect import inference
from gg import sequence,card,select_card,to_num,to_card
from pynput.keyboard import Controller, Key, Listener
import threading

WINDOW_TITLE = 'EVCapture4.1.4软件录制 - VLC media player'#"腾讯手游助手【极速傲引擎-7.1】"
tips = [('出牌','player'),('不叫','no'),('1分','onepoint'),('2分','twopoint'),('3分','threepoint'),
    ('可以点击不出','isnotout'),('可以点击提示','istips'),('可以点击出牌','isout'),('要不起','notget'),
    ('返回','return'),('再来一局','again'),('不可点击不出','notisnotout'),('不可点击提示','notistips'),
    ('不可点击出牌','notisout'),('A','one'),('2','two'),('3','three'),('4','four'),('5','five'),('6','six'),
    ('7','seven'),('8','eight'),('9','nine'),('10','ten'),('J','jack'),('Q','queen'),('K','king'),
    ('小王','ruler'),('大王','bigruler')]

def mousemove_click(x, y):
    autopy.mouse.smooth_move(x, y)
    autopy.mouse.click()

def threshold_pic(path):  # 二值化
    for root, dirs, files in os.walk(path):
        for file in files:
            filepath = os.path.join(root, file)
            if filepath.endswith('.bmp'):
                src = cv2.imread(filepath, 0)
                _, src = cv2.threshold(src, 200, 0, cv2.THRESH_BINARY)
                cv2.imwrite(filepath, src)
def start_listener():
    with Listener(on_press=lambda x:x, on_release=lambda x: exit(0) if x == Key.esc else x) as listener:
        listener.join()

def detect_pic(detect,img):
    card,temp = [],[]
    ret = detect.forward(img)
    if len(ret)>0:
        ret.sort(key=lambda x:x[6],reverse=True)
        for it in ret:
            card.append(tips[it[0]][0])
            temp.append([(it[1]+it[3]//2)*img.shape[1],(it[2]+it[4]//2)*img.shape[0]])
        return [card,temp]
    else:
        return [[],[]]

def click_item(name,data):
    if name in data[0]:
        i = data[0].index(name)
        pyautogui.click(x=data[1][i][0],y=data[1][i][1],duration=0.5)
        data[0].pop(i)
        data[1].pop(i)
        return True
    return False

def correct_pos(data,x,y):
    for it in data[1]:
        it[0]+=x
        it[1]+=y

pyautogui.FAILSAFE = False
if __name__ == '__main__':
    threading.Thread(target=start_listener)
    window = win32gui.FindWindow(None, WINDOW_TITLE)
    if window == 0:exit(0)
    #win32gui.ShowWindow(window, win32con.SW_SHOWNORMAL)
    #win32gui.SetForegroundWindow(window)
    pos = win32gui.GetClientRect(window)
    x, y = win32gui.ClientToScreen(window, (pos[0], pos[1]))
    pos = (pos[0]+x, pos[1]+y, pos[2], pos[3])
    if pos == None: 
        print("窗口定位失败")
        exit(0)    

    dizhu,first = '',True
    with torch.no_grad():
        while True:
            src = cv2.cvtColor(np.asarray(pyautogui.screenshot(region=pos)), cv2.COLOR_BGR2RGB)
            img_left = src[src.shape[0]*180//812: src.shape[0]*340//812,
                   src.shape[1]*240//1368: src.shape[1]*800//1368]
            img_right = src[src.shape[0]*180//812: src.shape[0]*340//812,
                            src.shape[1]*600//1368: src.shape[1]*1124//1368]
            img_bottom = src[src.shape[0]*500//812: src.shape[0]*812//812,
                            src.shape[1]*100//1368: src.shape[1]*1300//1368]
            img_button = src[src.shape[0]*440//812: src.shape[0]*520//812,
                            src.shape[1]*100//1368: src.shape[1]*1300//1368]

            img_list = [img_left,img_right,img_bottom,img_button]
            for i in img_list:cv2.imwrite(str(img_list.index(i)+1)+'.bmp',i)

            detect = inference()
            card1 = detect_pic(detect,img_left)
            correct_pos(card1,src.shape[1]*240//1368,src.shape[0]*180//812)
            if len(card1[0])>0: print('--------上家出牌:',card1[0])
            card2 = detect_pic(detect,img_right)
            correct_pos(card2,src.shape[1]*600//1368,src.shape[0]*180//812)
            if len(card2[0])>0: print('--------下家出牌:',card2[0])
            card3 = detect_pic(detect,img_bottom)
            correct_pos(card3,src.shape[1]*100//1368,src.shape[0]*500//812)
            if '再来一局' in card3[0]:
                first = True
                click_item('再来一局',card3)
            elif len(card3[0])>0:
                if first == True:dizhu = 'left' if len(to_num(card1[0]))>0 else ('right' if len(to_num(card2[0]))>0 else 'me')
                ret = select_card(to_num(card1[0] if len(card1[0]) else card2[0]), to_num(card3[0]), dizhu)
                first = False
                out = to_card(ret)
                print('--------你出牌:',out)
                for it in out: click_item(it,card3)
                option = detect_pic(detect,img_button)
                correct_pos(option,src.shape[1]*100//1368,src.shape[0]*500//812)
                if click_item('可以点击出牌',option)!=True:
                    if click_item('可以点击提示',option)==True:
                        click_item('可以点击出牌',option)
                click_item('可以点击不出',option)
                click_item('要不起',option)
                        
                
